﻿using BaiduApi.Entities;
using Core.Formats;
using Core.ReadWriter;
using Core.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaiduApi
{
    public class Oauth : BaseService
    {
        private static readonly JsonFormat JsonFormat;

        static Oauth()
        {
            JsonFormat = new JsonFormat();
        }

        private readonly string client_id;
        private readonly string client_secret;
        private readonly object expires_out_lock;

        private string access_token;
        private DateTime expires_out;

        public Oauth(string client_id, string client_secret)
        {
            this.client_id = client_id;
            this.client_secret = client_secret;

            expires_out_lock = new object();
        }

        public string AccessToken
        {
            get
            {
                if (DateTime.Now >= expires_out)
                {
                    lock (expires_out_lock)
                    {
                        if (DateTime.Now >= expires_out)
                        {
                            var ResultText = GetRequest("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=IThZ2QT5uyMcXTic7Cutf37m&client_secret=X0TpHQ5wtLQKNGBvm6n91ksjWPF1p0ft");

                            var Result = JsonFormat.Decode<TokenResult>(ResultText);

                            if (Result.error != null)
                            {
                                throw new Exception("获得 AccessToken 失败，错误码：" + Result.error + "，错误信息：" + Result.error_description);
                            }

                            access_token = Result.access_token;

                            expires_out = DateTime.Now.AddSeconds(Result.expires_in);
                        }
                    }
                }

                return access_token;
            }
        }
    }
}
